/**
 * 
 */
package edu.hadassah.prettyprint.config;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;


/**
 * @author persikov
 *
 */
public class ApplicationContextUtils {

	private static final String OUTPUT_NO_ATTRIBUTES = "-na";
	private static final String OUTPUT_NO_COMMENTS = "-nc";


	/**
	 * @param args
	 * @param xmlPrinterConfig
	 * @throws IOException 
	 */
	private static void fillOutputParams(String[] args,
			DocumentPrinterConfig xmlPrinterConfig) throws IOException {
		for (int i = 0; i < args.length-1; i++) {
			String cmdArgument = args[i];
			if ( cmdArgument.equals(ApplicationContextUtils.OUTPUT_NO_COMMENTS)){
				xmlPrinterConfig.setOutputComments(false);
			} else if ( cmdArgument.equals(ApplicationContextUtils.OUTPUT_NO_ATTRIBUTES)){
				xmlPrinterConfig.setOutputAttributes(false);
			} else {
				throw new IOException("Uknown argument : [" + cmdArgument +"]");
			}
		}
	}

	/**
	 * @param args
	 * @return
	 * @throws IOException 
	 */
	public static IDocumentPrinterConfig getDocumentConfig(String[] args) throws IOException {
		DocumentPrinterConfig xmlPrinterConfig = new DocumentPrinterConfig();
		int argNum = args.length;
		if ( argNum >= 1 && argNum < 4){
			String inputFilename = ApplicationContextUtils.getInputFilename(args);
			xmlPrinterConfig.setInputFileName(inputFilename);
			xmlPrinterConfig.setOutputFileName(inputFilename.substring(0, inputFilename.lastIndexOf('.')+1) + "html");
			if(argNum > 1){
				ApplicationContextUtils.fillOutputParams(args, xmlPrinterConfig); 
			}
			return xmlPrinterConfig;

		}
		throw new IOException("Wrong number of arguments : " + Arrays.toString(args));
	}
	/**
	 * @param args
	 * @return
	 * @throws IOException 
	 */
	private static String getInputFilename(String[] args) throws IOException {
		String inputFilename = args[args.length-1];
		if (inputFilename.endsWith(".xml")){
			File inputFile = new File(inputFilename);
			if ( inputFile.isFile() ){
				return inputFilename;
			}
		}
		throw new IOException("Failed to read from defined input file : " + inputFilename);
	}

}